package com.example.goods_manage.service.impl;

import com.example.goods_manage.dto.Goods;
import com.example.goods_manage.dto.GoodsUpdateRequest;
import com.example.goods_manage.dto.request.GoodsInsertRequest;
import com.example.goods_manage.dto.request.GoodsRequest;
import com.example.goods_manage.mapper.GoodsMapper;
import com.example.goods_manage.service.GoodsService;
import com.example.goods_manage.utils.AjaxResult;
import com.example.goods_manage.utils.PageUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <P> @Author: SongKeCheng
 * <P> Type: Class
 * <P> Description:
 * <P> Date: 2024/12/20:15:14
 */

@SuppressWarnings({"unchecked", ""})
@Service
public class GoodsServiceImpl implements GoodsService {
    private static final Logger log = LoggerFactory.getLogger(GoodsServiceImpl.class);

    @Autowired
    private GoodsMapper goodsMapper;

    /**
     * 1.进行分页
     * 2.查询数据库
     * 3.获取分页后的数据
     * 4.返回数据
    */
    @Override
    public AjaxResult findGoods(GoodsRequest goodsRequest) {
        PageHelper.startPage(goodsRequest.getPage(),goodsRequest.getLimit());
        List<Goods> goodsList =  goodsMapper.findGoods(goodsRequest);
        PageInfo<Goods> pageInfo = PageInfo.of(goodsList);
        PageUtils pageUtils = new PageUtils(pageInfo);
        return AjaxResult.success(pageUtils);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult addGoods(GoodsInsertRequest insertRequest) {
        Goods goods = new Goods();
        //进行属性copy
        BeanUtils.copyProperties(insertRequest,goods);
        int result =  goodsMapper.insertGoods(goods);
        if(result > 0 ){
            return AjaxResult.success("新增数据成功");
        }else {
            return AjaxResult.success("新增数据失败");
        }
    }

    @Override
    public AjaxResult findById(GoodsRequest goodsRequest) {
        Goods goods = goodsMapper.findGoodsById(goodsRequest.getId());
        return AjaxResult.success(goods);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updateGoods(GoodsUpdateRequest goodsUpdateRequest) {
        Goods goods = new Goods();
        BeanUtils.copyProperties(goodsUpdateRequest,goods);
        int updateResult = goodsMapper.updateByPrimaryKeySelective(goods);
        if(updateResult > 0 ){
            return AjaxResult.success("更新数据成功");
        }else {
            return AjaxResult.success("更新数据失败");
        }
    }
}
